//
//  PlaceDetailVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/17.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
import EasyNavigation
import AVKit
import WebKit


class PlaceDetailVC: UIViewController {

    var cateVo:CategoryVo?
    var cellContView:UIView?
    var html:String?
    var webview:UIWebView?
    var DHeight:Float =  0.00
    var dataArray:Array<CommentVo> = Array()
    let sendBtn = UIButton()
    private var detailView:UIView = UIView()
    var playerCtrl:AVPlayerViewController?
    var fromRoute = false


    var page = 1
    func sendRequest() {
        
        API.projectCommentList(params: ["page":"1",
                                        "projectId":self.cateVo!.platfromProject!.id!]) { (result) in
            
                          self.handleResult(pageVo: result as! Page<CommentVo>)

        }
        

    }
    
    func handleResult(pageVo:Page<CommentVo>){
        
        //self.tableView.mj_header.endRefreshing()
        self.dataArray = pageVo.list

        
        

        self.tableView.reloadData()
        
    }


    lazy var navView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: HT_StatusBarAndNavigationBarHeight)
        
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_white"), for: .normal)
        backBtn.addTarget(self, action: #selector(backClick), for: .touchUpInside)
        bg.addSubview(backBtn)
        let _ = backBtn.sd_layout()?.leftSpaceToView(bg,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        
        let moreBtn = UIButton()
        moreBtn.setImage(UIImage(named: "more_white"), for: .normal)
        moreBtn.addTarget(self, action: #selector(moreBtnClick), for: .touchUpInside)
        bg.addSubview(moreBtn)
        let _ = moreBtn.sd_layout()?.rightSpaceToView(bg,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        
        
        let shareBtn = UIButton()
        shareBtn.setImage(UIImage(named: "share_white"), for: .normal)
        shareBtn.addTarget(self, action: #selector(shareBtnClick), for: .touchUpInside)
        bg.addSubview(shareBtn)
        let _ = shareBtn.sd_layout()?.rightSpaceToView(moreBtn,10)!.heightIs(35)!.topSpaceToView(bg,HT_StatusBarHeight)!.widthIs(35)
        shareBtn.isHidden = true
        moreBtn.isHidden = true
        
        return bg
        
        
    }()
    
    
    lazy var HeaderView:UIView = {
        
        var namehei = self.cateVo?.platfromProject?.proName?.replacingOccurrences(of: "#", with: " ").stringHeightWith(fontSize: 25, width: KScreenWidth-32)
        let hei = KScreenWidth*9/16
        let bg = UIView()
        bg.backgroundColor = UIColor.backgroundColor
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: CGFloat(hei)+175+namehei!)

        let playBg = UIView()
        bg.addSubview(playBg)
        let _ = playBg.sd_layout()?.widthRatioToView(bg,1)!.heightIs(CGFloat(hei))!.topSpaceToView(bg,0)
        
        
        let videoImage = UIImageView()
        playBg.addSubview(videoImage)
        let _ = videoImage.sd_layout()?.widthRatioToView(playBg,1)!.heightIs(CGFloat(hei))!.topSpaceToView(playBg,0)
        
        

        if self.fromRoute == true && (self.cateVo?.platfromProject?.proVideo!.count)!>0{
            
            videoImage.image = BZHttpFileHelper.firstFrame(withVideoURL: URL(string:self.cateVo!.platfromProject!.proVideo!)!, size: CGSize(width: KScreenWidth, height: CGFloat(hei)))

            
        }else{
            
            if self.cateVo?.platfromProject?.posterImg?.starts(with: "http") == true {
                
                
                videoImage.sd_setImage(with: URL(string:(self.cateVo?.platfromProject?.posterImg)!), placeholderImage: UIImage(named: "holder_big"), options: .lowPriority) { (A, B, C, D) in
                    
                }

                
            }else{
                
                
                videoImage.sd_setImage(with: URL(string:("https://hqctv.oss-cn-beijing.aliyuncs.com/"+(self.cateVo?.platfromProject!.posterImg)!)), placeholderImage: UIImage(named: "holder_big"), options: .lowPriority) { (A, B, C, D) in
                    
                }
            }

            

        }
        let playBtn = UIButton()
        playBtn.setImage(UIImage(named: "playvideo"), for: .normal)
        playBg.addSubview(playBtn)
        let _ = playBtn.sd_layout()?.widthIs(55)!.heightIs(55)!.centerXEqualToView(playBg)!.centerYEqualToView(playBg)
        playBtn.addTarget(self, action: #selector(playBtnClick), for: .touchUpInside)
        
        if self.cateVo?.platfromProject?.proVideo?.count == 0{
            
            playBtn.isHidden = true
        }

        let infoView = UIView()
        infoView.backgroundColor = UIColor.white
        bg.addSubview(infoView)
        infoView.frame = CGRect(x: 0, y: CGFloat(hei)-15, width: KScreenWidth, height: 180+namehei!)
        infoView.SetMutiBorderRoundingCornersTLTR(infoView, corner: 20)
        
        let nameLab = UILabel()
        infoView.addSubview(nameLab)
        nameLab.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight(rawValue: 0.2))
        
        nameLab.textColor = UIColor.textTitleColorBlack
        nameLab.text = self.cateVo?.platfromProject?.proName?.replacingOccurrences(of: "#", with: " ")
        let _ = nameLab.sd_layout()?.leftSpaceToView(infoView,16)?.autoHeightRatio(0)?.rightSpaceToView(infoView,16)?.topSpaceToView(infoView,20)
        nameLab.setMaxNumberOfLinesToShow(3)
        
        let infoLab = UILabel()
        infoView.addSubview(infoLab)
        infoLab.font = UIFont.smallerFont
        infoLab.textColor = UIColor.init(hexString: "#999999")
        infoLab.text = ""
        let _ = infoLab.sd_layout()?.leftSpaceToView(infoView,16)?.heightIs(15)?.rightSpaceToView(infoView,16)?.topSpaceToView(nameLab,1)
        
        
        let tags = self.cateVo?.platfromProject?.tag?.split(string: ",")
        infoLab.updateLayout()
        let tagsView = STTagsView.tagView(withFrame: CGRect(x: 14, y: infoLab.frame.maxY-5, width: infoView.width-40, height: 15), tagsArray: tags, textColor: UIColor.GP_Blue_Color, textFont: UIFont .systemFont(ofSize: 10), normalTagBackgroundColor: UIColor.backgroundColor, tagBorderColor: UIColor.GP_Blue_Color, contentInsets: UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5), labelContentInsets: UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3), labelHorizontalSpacing: 5, labelVerticalSpacing: 5)
        infoView.addSubview(tagsView!)
        
        
        let addrBtn = UIButton()
        infoView.addSubview(addrBtn)
        let _ = addrBtn.sd_layout()?.leftSpaceToView(infoView,16)!.rightSpaceToView(infoView,16)!.topSpaceToView(infoLab,28)!.heightIs(40)
        
        
        let icon = UIImageView()
        icon.image = UIImage(named: "addr_11")
        addrBtn.addSubview(icon)
        let _ = icon.sd_layout()?.widthIs(18)!.heightIs(18)!.leftSpaceToView(addrBtn,0)!.centerYEqualToView(addrBtn)
        let adrLab = UILabel()
        addrBtn.addSubview(adrLab)
        adrLab.font = UIFont.commonFontSmaller
        adrLab.textColor = UIColor.textTitleColorBlack
        adrLab.text = self.cateVo?.platfromProject?.proAddress
        let _ = adrLab.sd_layout()?.leftSpaceToView(addrBtn,25)?.heightIs(15)?.rightSpaceToView(addrBtn,16)?.centerYEqualToView(addrBtn)
        
        let bottView = UIView()
        infoView.addSubview(bottView)
        bottView.backgroundColor = UIColor.white
        let _ = bottView.sd_layout()?.widthRatioToView(infoView,1)!.heightIs(64)!.topSpaceToView(addrBtn,0)

        let phoneBtn = UIButton()
        phoneBtn.addTarget(self, action: #selector(phoneClick), for: .touchUpInside)
        bottView.addSubview(phoneBtn)
        let _ = phoneBtn.sd_layout()?.widthIs(80)!.heightIs(30)!.topSpaceToView(bottView,10)!.centerXEqualToView(bottView)
        phoneBtn.setTitle("电话", for: .normal)
        phoneBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        phoneBtn.titleLabel?.font = UIFont.smallerFont
        
        let icon11bg = UIView()
        icon11bg.isUserInteractionEnabled = false
        phoneBtn.addSubview(icon11bg)
        icon11bg.sd_cornerRadius = 14
        icon11bg.backgroundColor = UIColor.init(hexString: "#eaf0fc")
        let _  = icon11bg.sd_layout()?.widthIs(28)!.heightIs(28)!.topSpaceToView(phoneBtn,0)!.centerXEqualToView(phoneBtn)

        
        let icon11 = UIImageView()
        icon11.image = UIImage(named: "phone_sml")
        icon11bg.addSubview(icon11)
        let _  = icon11.sd_layout()?.widthIs(16)!.heightIs(16)!.centerYEqualToView(icon11bg)!.centerXEqualToView(icon11bg)
        let _ = phoneBtn.titleLabel?.sd_layout()?.widthIs(45)!.heightIs(20)!.centerXEqualToView(phoneBtn)!.topSpaceToView(phoneBtn,28)
        phoneBtn.titleLabel?.textAlignment = .center
        
        

        let navBtn = UIButton()
        navBtn.addTarget(self, action: #selector(navClick), for: .touchUpInside)
        bottView.addSubview(navBtn)
        let _ = navBtn.sd_layout()?.widthIs(80)!.heightIs(30)!.topSpaceToView(bottView,10)!.rightSpaceToView(phoneBtn,65)
        navBtn.setTitle("导航", for: .normal)
        navBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        navBtn.titleLabel?.font = UIFont.smallerFont
        
        let icon2bg = UIView()
        icon2bg.isUserInteractionEnabled = false
        navBtn.addSubview(icon2bg)
        icon2bg.sd_cornerRadius = 14
        icon2bg.backgroundColor = UIColor.init(hexString: "#eaf0fc")
        let _  = icon2bg.sd_layout()?.widthIs(28)!.heightIs(28)!.topSpaceToView(navBtn,0)!.centerXEqualToView(navBtn)

        
        let icon2 = UIImageView()
        icon2.image = UIImage(named: "nav_sml")
        icon2bg.addSubview(icon2)
        let _  = icon2.sd_layout()?.widthIs(16)!.heightIs(16)!.centerYEqualToView(icon2bg)!.centerXEqualToView(icon2bg)
        let _ = navBtn.titleLabel?.sd_layout()?.widthIs(45)!.heightIs(20)!.centerXEqualToView(navBtn)!.topSpaceToView(navBtn,28)
        navBtn.titleLabel?.textAlignment = .center
        
        

        let carBtn = UIButton()
        carBtn.addTarget(self, action: #selector(rentCarClick), for: .touchUpInside)
        bottView.addSubview(carBtn)
        
        let _ = carBtn.sd_layout()?.widthIs(80)!.heightIs(30)!.topSpaceToView(bottView,10)!.leftSpaceToView(phoneBtn,65)
        carBtn.setTitle("租车", for: .normal)
        
        
        let icon3bg = UIView()
        icon3bg.isUserInteractionEnabled = false

        carBtn.addSubview(icon3bg)
        icon3bg.sd_cornerRadius = 14
        icon3bg.backgroundColor = UIColor.init(hexString: "#eaf0fc")
        let _  = icon3bg.sd_layout()?.widthIs(28)!.heightIs(28)!.topSpaceToView(carBtn,0)!.centerXEqualToView(carBtn)

        
        let icon3 = UIImageView()
        icon3.image = UIImage(named: "car_sml")
        icon3bg.addSubview(icon3)
        let _  = icon3.sd_layout()?.widthIs(13)!.heightIs(13)!.centerYEqualToView(icon3bg)!.centerXEqualToView(icon3bg)


        carBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
        carBtn.titleLabel?.font = UIFont.smallerFont
        let _ = carBtn.titleLabel?.sd_layout()?.widthIs(45)!.heightIs(20)!.centerXEqualToView(carBtn)!.topSpaceToView(carBtn,28)
        carBtn.titleLabel?.textAlignment = .center
        
        
        return bg
        
    }()
    lazy var bottomView:UIView = {
        
        let bigBg = UIView()
        bigBg.backgroundColor = UIColor.white
        
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bigBg.addSubview(bg)
        let _ = bg.sd_layout()?.widthRatioToView(bigBg,1)?.heightIs(55)!.bottomSpaceToView(bigBg,HT_TabbarSafeBottomMargin)
        
        let commBtnBg = UIButton()
        commBtnBg.sd_cornerRadius = 16
        bg.addSubview(commBtnBg)
        commBtnBg.addTarget(self, action: #selector(showCommentAlert), for: .touchUpInside)
        commBtnBg.backgroundColor = UIColor.backgroundColor
        let icon = UIImageView()
        icon.image = UIImage(named: "写评论")
        commBtnBg.addSubview(icon)
        let _ = icon.sd_layout()?.widthIs(14)!.heightIs(13)?.centerYEqualToView(commBtnBg)!.leftSpaceToView(commBtnBg,16)
        
        let lab = UILabel()
        lab.font = UIFont.commonFontSmaller
        lab.textColor = UIColor.init(hexString: "#b2b2b2")
        lab.text = "说点啥..."
        commBtnBg.addSubview(lab)
        let _ = lab.sd_layout()?.leftSpaceToView(icon,10)!.heightIs(20)!.centerYEqualToView(commBtnBg)!.widthIs(75)
        
        let shareBtn = UIButton()
        shareBtn.addTarget(self, action: #selector(shareClick), for: .touchUpInside)
        shareBtn.setImage(UIImage(named: "分享"), for: .normal)
        bg.addSubview(shareBtn)
        let _ = shareBtn.sd_layout()?.rightSpaceToView(bg,16)!.centerYEqualToView(bg)!.widthIs(23)!.heightIs(22)
        
        
        
        
        let commentBtn = UIButton()
        commentBtn.addTarget(self, action: #selector(gotoZIXUN), for: .touchUpInside)
        commentBtn.setImage(UIImage(named: "评论"), for: .normal)
        commentBtn.titleLabel?.font = UIFont.smallerLessthanFont
        commentBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
        bg.addSubview(commentBtn)
        let _ = commentBtn.sd_layout()?.rightSpaceToView(shareBtn,15)?.centerYEqualToView(bg)?.widthIs(23)!.heightIs(23)
        
        
//        let _ = commentBtn.imageView?.sd_layout()?.widthIs(23)?.heightIs(22)?.leftSpaceToView(commentBtn,0)?.centerYEqualToView(commentBtn)
//
//        let _ = commentBtn.titleLabel?.sd_layout()?.heightIs(15)?.leftSpaceToView(commentBtn.imageView,5)?.widthIs(45)?.centerYEqualToView(commentBtn)
//        commentBtn.titleLabel?.textAlignment = .left
        
        let favBtn = UIButton()
        favBtn.addTarget(self, action: #selector(favClick), for: .touchUpInside)
         favBtn.setImage(UIImage(named: "收藏"), for: .normal)
        favBtn.setImage(UIImage(named: "faved"), for: .selected)
         favBtn.titleLabel?.font = UIFont.smallerLessthanFont
         favBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
         bg.addSubview(favBtn)
        let _ = favBtn.sd_layout()?.rightSpaceToView(commentBtn,15)?.centerYEqualToView(bg)?.widthIs(23)!.heightIs(23)
        
        let _ = commBtnBg.sd_layout()?.heightIs(32)!.rightSpaceToView(favBtn,35)?.centerYEqualToView(bg)?.leftSpaceToView(bg,16)

         
         
//         let _ = favBtn.imageView?.sd_layout()?.widthIs(23)?.heightIs(22)?.rightSpaceToView(favBtn,0)?.centerYEqualToView(favBtn)
//
//         let _ = favBtn.titleLabel?.sd_layout()?.heightIs(15)?.leftSpaceToView(favBtn.imageView,5)?.widthIs(45)?.centerYEqualToView(favBtn)
//         favBtn.titleLabel?.textAlignment = .left
        
        
        
        return bigBg
        
    }()
    lazy var tableView:UITableView = {
        
        
        var tableView = UITableView()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.white
        tableView.tableFooterView = UIView()
        tableView.separatorColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.tableHeaderView = self.HeaderView
        tableView.register(UINib.init(nibName: "CommentCell", bundle: nil), forCellReuseIdentifier: "CommentCell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellid")

        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        
        self.cellContView = self.createCellContent()
        self.html = self.createHtml()
        
        

        view.addSubview(self.tableView)
        let _ = self.tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 0, left: 0, bottom: HT_TabbarSafeBottomMargin+55+10, right: 0))
        
        self.view.addSubview(self.bottomView)
        self.bottomView.updateLayout()
        self.bottomView.layer.shadowOffset = CGSize(width: 5, height: 5)
        self.bottomView.layer.shadowOpacity = 1
        self.bottomView.layer.shadowColor = UIColor.lineColor.cgColor
        self.bottomView.layer.shadowRadius = 3
        let _ = self.bottomView.sd_layout()?.widthRatioToView(self.view,1)!.heightIs(55+HT_TabbarSafeBottomMargin)!.bottomSpaceToView(self.view,0)
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        }
        
        self.view.addSubview(self.navView)
        self.view.bringSubviewToFront(self.navView)
        
        self.tableView.reloadData()
        
//        let header = MJRefreshNormalHeader.init {
//
//            self.page = 1
//            self.sendRequest()
//        }
//        header?.stateLabel.isHidden = true
//        header?.lastUpdatedTimeLabel.isHidden = true
//        self.tableView.mj_header = header
        
//        let footer = MJRefreshAutoNormalFooter.init {
//
//            self.page += 1
//            self.sendRequest()
//        }
//        self.tableView.mj_footer = footer
        
        sendRequest()
        
        
    }
    
    
    @objc func shareClick(){
        
        
        let img0 = BZHttpFileHelper.imageWithScreenshot()
        let img1 = BZHttpFileHelper.compressImage(img0, toByte: 50*1024)

        let shareItems:Array = [img1 as Any] as [Any]
                let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
                self.present(activityViewController, animated: true, completion: nil)

    }
    @objc func rentCarClick(btn: UIButton){
        
        var actions: Array<PopoverAction> = [PopoverAction]()
         for item in ["境内","境外"] {
             
             let action = PopoverAction.init(title: item) { (action) in
                 
                 let vo = action?.model as! String
                if vo == "境内"{
                    
                    let web = WebViewController()
                    web.myTitle = "租车"
                    web.url = Constant.RENTCAR_URL
                    PUSH(from: self, to: web)
                    
                }else{
                    
                    let web = WebViewController()
                    web.myTitle = "租车"
                    web.url = Constant.RENTCAR_FOREIGN_URL
                    PUSH(from: self, to: web)
                    
                }
                 
                 
                 
             }
             action?.model = item
             actions.append(action!)
             
         }
         let popView = PopoverView.init()
         popView.hideAfterTouchOutside = true
         popView.style = .default
        popView.showShade = true
        popView.show(to: btn, with: actions)
        
    }
    @objc func phoneClick(){
        
        if self.cateVo?.platfromProject?.mobile?.isEmpty == true {
            
            ToastUtil.show(msg: "电话暂未提供")
            return
        }
        let phone = self.cateVo?.platfromProject?.mobile
        ToastUtil.showAlert(context: self, title: "提示", msg: "是否拨打电话\(phone ?? Constant.PHONE)", sureTitle: "拨打") {
            
            let str = String(format: "tel://%@", phone!)
            UIApplication.shared.openURL(URL(string: str)!)
        }
        
    }
    @objc func playBtnClick(){
        
        
        self.playerCtrl = AVPlayerViewController()
        let asset = AVAsset(url: URL(string: self.cateVo!.platfromProject!.proVideo!)!)
        let pitem = AVPlayerItem(asset: asset)
        self.playerCtrl?.player = AVPlayer(playerItem: pitem)
        self.playerCtrl?.videoGravity = .resizeAspectFill
        self.playerCtrl?.player?.play()
        self.playerCtrl?.showsPlaybackControls = true
        self.playerCtrl?.view.bounds = CGRect(x: 0, y: 0, width: KScreenWidth, height: 210)
        self.view.addSubview(self.playerCtrl!.view)
        self.view.bringSubviewToFront(self.playerCtrl!.view)
        
        self.present(self.playerCtrl!, animated: true) {
            
        }
    }
    
    
    let bg = UIView()
    let inputV = GCPlaceholderTextView()

        
   @objc func showCommentAlert() {
        
        self.view.addSubview(bg)
        let _  = bg.sd_layout()?.spaceToSuperView(.zero)

        let bgImgv = UIImageView()
        bgImgv.alpha = 0.5
        bgImgv.backgroundColor = UIColor.init(patternImage: UIImage(named: "paybg")!)
        bg.addSubview(bgImgv)
        let _ = bgImgv.sd_layout()?.spaceToSuperView(.zero)
        
        let bg2 = UIView()
    bg2.backgroundColor = UIColor.white
        bg.addSubview(bg2)
        let _ = bg2.sd_layout()?.bottomSpaceToView(bg,0)?.widthRatioToView(bg,1)?.heightIs(166)
    
    bg2.addSubview(inputV)
    inputV.placeholder = "发表评论"
    inputV.sd_cornerRadius = 3
    inputV.delegate = self
    inputV.font = UIFont.commonFontSmall
    inputV.textColor = UIColor.textTitleColorBlack
    let _ = inputV.sd_layout()?.leftSpaceToView(bg2,16)!.rightSpaceToView(bg2,16)!.heightIs(90)!.topSpaceToView(bg2,25)
    inputV.layer.borderColor = UIColor.lineColor.cgColor
    inputV.layer.borderWidth = 0.5
    inputV.becomeFirstResponder()
    
    sendBtn.setTitle("发送", for: .normal)
    sendBtn.isEnabled = false
    sendBtn.addTarget(self, action: #selector(sendBtnClick), for: .touchUpInside)
    sendBtn.setTitleColor(UIColor.textPlaceHolderColor, for: .normal)
    sendBtn.titleLabel?.font = UIFont.commonFontSmall
    bg2.addSubview(sendBtn)
    
    let _ = sendBtn.sd_layout()?.rightSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
    
    let cancelBtn = UIButton()
    cancelBtn.setTitle("取消", for: .normal)
    cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
    cancelBtn.setTitleColor(UIColor.GP_Red_Color, for: .normal)
    cancelBtn.titleLabel?.font = UIFont.commonFontSmall
    bg2.addSubview(cancelBtn)
    
    let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg2,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(inputV,5)
    
    
    
        
    }
    @objc func favClick(btn:UIButton){
        
        if SPUtil.init().loginStatus == 0 {
            
            APP.backToVC = self
            PUSH(from: self, to: LoginViewController())
            return
        }
        if SPUtil.init().mobile.count == 0 {
            
            APP.backToVC = self
            PUSH(from: self, to: BindPhoneVC())
            return
      
        }
        
        API.collect(params: ["type":"COL",
                             "mobile":SPUtil.init().mobile!,
                             "colType":"PLACE",
                             "pdtId":self.cateVo!.platfromProject!.id!]) { (result) in
            
            
                                ToastUtil.show(msg: "收藏成功")
        }
        btn.isSelected.toggle()
        
    }
    @objc func gotoZIXUN(){
        

        
        let zivc = CommentSampleVC()
        zivc.type = "project"
        zivc.pid =  self.cateVo?.platfromProject?.id
        self.present(EasyNavigationController(rootViewController: zivc), animated: true) {
            
        }

        
    }

    @objc func closeBtnClick(){
        
        self.detailView.removeFromSuperview()
        
    }
    
    @objc func sendBtnClick(){
        
          if SPUtil.init().loginStatus == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: LoginViewController())
              return
          }
          if SPUtil.init().mobile.count == 0 {
              
              APP.backToVC = self
              PUSH(from: self, to: BindPhoneVC())
              return
        
          }
        
        if inputV.text.count == 0 {
            
            ToastUtil.showHUDWarn(msg: "随便写点什么吧")
            return
        }
        
        API.projectComment(params: [
            "pdtId":self.cateVo!.platfromProject!.id!,
            "mobile":SPUtil.init().mobile!,
            "content":inputV.text!]) { (result) in
            
                                        ToastUtil.show(msg: "评论已提交")
                                        self.bg.removeFromSuperview()
                                        

        }
        
    }
    @objc func cancelBtnClick(){
        
        bg.removeFromSuperview()
    }
    
    @objc func navClick(){
        
        let alertSheet = UIAlertController(title: "导航地图", message: "请选择", preferredStyle: .actionSheet)
        // 2 命令（样式：退出Cancel，警告Destructive-按钮标题为红色，默认Default）

        let ac1 = UIAlertAction(title: "百度地图", style: .default, handler: { (action) in
            
            BZHttpFileHelper.fileHelperShareInstance().gotoMap(self.cateVo?.platfromProject?.latitude ?? "", longt: self.cateVo?.platfromProject?.longitude ?? "", addr: self.cateVo?.platfromProject?.proAddress ?? "",type: "baidu")

        })
        ac1.setValue(UIColor.textTitleColorBlack, forKey: "titleTextColor")
        alertSheet.addAction(ac1)
        
        
        let ac2 = UIAlertAction(title: "腾讯地图", style: .default, handler: { (action) in
            
            BZHttpFileHelper.fileHelperShareInstance().gotoMap(self.cateVo?.platfromProject?.latitude ?? "", longt: self.cateVo?.platfromProject?.longitude ?? "", addr: self.cateVo?.platfromProject?.proAddress ?? "",type: "qqmap")

        })
        ac2.setValue(UIColor.textTitleColorBlack, forKey: "titleTextColor")
        alertSheet.addAction(ac2)
        
        
        let ac3 = UIAlertAction(title: "Google 地图", style: .default, handler: { (action) in
            
            BZHttpFileHelper.fileHelperShareInstance().gotoMap(self.cateVo?.platfromProject?.latitude ?? "", longt: self.cateVo?.platfromProject?.longitude ?? "", addr: self.cateVo?.platfromProject?.proAddress ?? "",type: "google")

        })
        ac3.setValue(UIColor.textTitleColorBlack, forKey: "titleTextColor")
        alertSheet.addAction(ac3)
        
        let ac4 = UIAlertAction(title: "高德地图", style: .default, handler: { (action) in
            
            BZHttpFileHelper.fileHelperShareInstance().gotoMap(self.cateVo?.platfromProject?.latitude ?? "", longt: self.cateVo?.platfromProject?.longitude ?? "", addr: self.cateVo?.platfromProject?.proAddress ?? "",type: "gaode")
        })
        ac4.setValue(UIColor.textTitleColorBlack, forKey: "titleTextColor")
        alertSheet.addAction(ac4)
            
        let ac5 = UIAlertAction(title: "Apple 地图", style: .default, handler: { (action) in
            
            BZHttpFileHelper.fileHelperShareInstance().gotoMap(self.cateVo?.platfromProject?.latitude ?? "", longt: self.cateVo?.platfromProject?.longitude ?? "", addr: self.cateVo?.platfromProject?.proAddress ?? "",type: "ios")
        })
        ac5.setValue(UIColor.textTitleColorBlack, forKey: "titleTextColor")
        alertSheet.addAction(ac5)

        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.destructive, handler: nil)
        alertSheet.addAction(cancelAction)

        
        // 3 跳转
        self.present(alertSheet, animated: true, completion: nil)
        
        
        
        
    }
    
    @objc func backClick(){
        
        POP(vc: self)
    }
    @objc func moreBtnClick(){
        
    }
    @objc func shareBtnClick(){

        let img0 = BZHttpFileHelper.imageWithScreenshot()
        let img1 = BZHttpFileHelper.compressImage(img0, toByte: 50*1024)

        let shareItems:Array = [img1 as Any] as [Any]
                let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
        activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]
                self.present(activityViewController, animated: true, completion: nil)
        
    }
    

    

}

extension PlaceDetailVC:UITableViewDelegate,UITableViewDataSource,WKNavigationDelegate,UIWebViewDelegate,WKUIDelegate,UITextViewDelegate{
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        let yOffset = scrollView.contentOffset.y
        print("\(yOffset)")
        if yOffset > HT_StatusBarAndNavigationBarHeight {
            
            self.navView.isHidden = true
        }
        if yOffset <= 0 {
            
            self.navView.isHidden = false
        }

    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        if inputV.text.count > 3 {
            
            sendBtn.isEnabled = true
            sendBtn.setTitleColor(UIColor.btnMainColor, for: .normal)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            
            return 1
            
            
        }else{
            
            return self.dataArray.count

        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            return CGFloat(self.DHeight+80)

            
        }else{
            
            let mod = self.dataArray.get(at: indexPath.row)
            
            let cnt = mod?.content
            let height  = cnt!.stringHeightWith(fontSize: 14, width: KScreenWidth-64-16)
            
            return 50+height+32
            
        }
    }
    

    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 1 {
            
            if self.dataArray.count == 0 {
                
                return 0
            }
            return 44

        }else{
            
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 44)
        let titleLab = UILabel()
        bg.addSubview(titleLab)
        titleLab.textColor = UIColor.textTitleColorBlack
        titleLab.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        titleLab.text = "评论"
        let _ = titleLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.centerYEqualToView(bg)!.rightSpaceToView(bg,16)
        return bg
    }
    

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell") as! CommentCell
            cell.setModel(mod: self.dataArray.get(at: indexPath.row)!)
            return cell
            
        }else{
            
            let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellid")!
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.white
            if webview == nil {
                
                /*let config = WKWebViewConfiguration()
                config.requiresUserActionForMediaPlayback = false
                config.allowsInlineMediaPlayback = true
                webview = WKWebView(frame: .zero, configuration: config)*/
                webview = UIWebView()
                cell.contentView.addSubview(webview!)
                let _ = webview!.sd_layout()?.spaceToSuperView(UIEdgeInsets(top: 0, left: 12, bottom: 10, right: 12))
                 
                webview!.backgroundColor = UIColor.white
                webview?.allowsInlineMediaPlayback = true
                webview?.mediaPlaybackRequiresUserAction = false
                webview!.isOpaque = false
                webview!.delegate = self
                //webview!.navigationDelegate = self
                webview!.scrollView.isScrollEnabled = false
                webview!.scrollView.backgroundColor = UIColor.white
                webview!.loadHTMLString(self.html!.resizeImageForHTML(), baseURL: nil)
                
            }

            return cell
        }

    }
//    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//
//        //self.DHeight = Float(webview!.stringByEvaluatingJavaScript(from: "document.body.offsetHeight")) as! Float
//        webView.evaluateJavaScript("document.body.offsetHeight") { (result, error) in
//
//            self.DHeight = Float(webView.scrollView.contentSize.height)
//            self.tableView.reloadData()
//
//        }
//
//
//    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        self.DHeight = Float(webview!.stringByEvaluatingJavaScript(from: "document.body.offsetHeight")!) as! Float
        self.tableView.reloadData()

    }

    
    func createHtml() -> String{
        
        var html = ""
        
        for item in self.cateVo!.projectDetailList! {
            
            
            
            if item.type == "text"  {
                
                let pNode = String(format: "<p style=\"text-align: justify; line-height: 1.5em;\"><span style=\"color: rgb(66, 66, 66); font-family: 宋体, SimSun;font-size:14px\">%@</span></p>", item.conUrl!.replacingOccurrences(of: "\n", with: "<br />"))
                html += pNode


            }else if item.type == "img"{
                

                let imgNode = String(format: "<p style=\"text-align: justify; line-height: 2em;\"><img title=\"\" alt=\"\" src=\"%@\"/></p>", item.conUrl!)
 
                html += imgNode
                
            }else if item.type == "video"{
                
                let videoNode = String(format: "<video controls poster=\"%@\" class=\"edui-upload-video  vjs-default-skin        video-js\" controls=\"\" preload=\"meta\" width=\"100%@\" height=\"280\" src=\"%@\"><source src=\"%@\" type=\"video/mp4\"/></video>", item.conUrl!,"%",item.videoUrl!,item.videoUrl!)
                html += videoNode

            }

        }
        return html
    }


    func createCellContent() -> UIView{
        
        let bg =  UIView()
        bg.backgroundColor = UIColor.white
        
        let containerView = UIView()
        bg.addSubview(containerView)
        containerView.backgroundColor = UIColor.white
        var temp = Array<UIView>()
        
        
        
        
        for item in self.cateVo!.projectDetailList! {
            
            
            
            if item.type == "text"  {
                
                let lab = UILabel()
                lab.text = item.conUrl
                containerView.addSubview(lab)
                let _ = lab.sd_layout()?.autoHeightRatio(0)
                lab.setMaxNumberOfLinesToShow(999)
                temp.append(lab)

            }else if item.type == "img"{
                
                let imgv = UIImageView()
                containerView.addSubview(imgv)
                let _ = imgv.sd_layout()?.heightIs(185)
                imgv.sd_setImage(with: URL(string:item.conUrl!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                temp.append(imgv)
                
            }else if item.type == "video"{
                
                let imgv = UIImageView()
                imgv.backgroundColor = UIColor.cccColor
                containerView.addSubview(imgv)
                let _ = imgv.sd_layout()?.heightIs(185)
                
                imgv.sd_setImage(with: URL(string:item.videoUrl!), placeholderImage: UIImage(named: "holder"), options: .lowPriority) { (A, B, C, D) in
                    
                }
                temp.append(imgv)
            }

        }
        let _ = containerView.sd_layout()?.topSpaceToView(bg,0)?.widthRatioToView(bg,1)
        
        containerView.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 1, verticalMargin: 0, horizontalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        
        bg.setupAutoHeight(withBottomView: containerView, bottomMargin: 10)
        bg.updateLayout()
        return bg
    }
    
}
